<?php

class ArticleController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
        public function actionApprove()
        {
            $form=new ApproveForm;
            if(isset($_POST[ApproveForm]))
            {
                $form->attributes=$_POST['ApproveForm'];
            }
            if($form->validate())
            {
                Yii::app()->user->setFlash('sucess',$form->article." has been proved");
                $form=new ApproveForm;
            }
            $article=  Article::model()->findAll();
            $this->render('approve',array(
                        'model'=>$model,

                                        )
                    );
        }
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
                        'updateContext + update',
                        'addUserContext + adduser',
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'create', 'update', 'delete','adduser'),
				'roles' => array('ADMIN'),
			),
                        array('allow',
                            'actions'=>array('update','adduser'),
                            'users'=>array('@'),
                        ),
                        array('allow',
                            'actions'=>array('index', 'view', 'create'),
                            'users'=>array('@'),
                        ),
//                        array('allow',
//                            'actions'=>array('update'),
//                            'roles' => array('editor', 'author'),
//                        ),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Article;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];
                        $model->create_time=$model->update_time=new CDbExpression('NOW()');
                        $model->author_id=Yii::app()->user->id;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

        public function filterUpdateContext($filterChain){
            $userid = Yii::app()->user->id;
            $currentarticle = Article::model()->findByPk($_GET["id"]);

            //if not AUTHOR Or EDITOR or ADMIN -> no access
            if ($userid == $currentarticle->author_id
                    || $userid == $currentarticle->editor_id
                    || $userid == $currentarticle->approver_id
                    || $userid == $this->getAdminId() ){
                //do nothing => means ok
            }
            else {
                throw new CHttpException(404, "You are not the author or editor
                     assigned to this article '" . $currentarticle->headline ."'
                     . Contact the author '" . $currentarticle->author->username.
                        "' for more information !!!");
            }

            $filterChain->run();
        }

        public function filterAddUserContext($filterChain){
            $userid = Yii::app()->user->id;
            $currentarticle = Article::model()->findByPk($_GET["id"]);

            //if not APPROVER or ADMIN -> no access
//            if ($userid == $currentarticle->approver_id
//                    || $userid == $this->getAdminId() ){
//                //do nothing
//            }
            if ($currentarticle->isUserInRole('approver')
                    || Yii::app()->user->checkAccess('ADMIN')){

            }
            else{
                throw new CHttpException(404, "Only approver and admin have right to access this page");
            }

            $filterChain->run();    
        }

        protected function getAdminId(){
            $sql = "SELECT userid FROM AuthAssignment WHERE itemname = 'ADMIN' ";
            $command = Yii::app()->db->createCommand($sql);
            return $command->execute();
        }

//        public function actionAddUser($id){
//            $model = $this->loadModel($id);
//
//            if (isset($_POST['Article'])){
//                $model->attributes = $_POST['Article'];
//                if ($model->save())
//                        $this->redirect(array('view', 'id'=> $model->id));
//            }
//
//            $this->render('adduser', array(
//                'model'=>$model,
//            ));
//        }

        public function actionAddUser($id){
             $form = new ArticleUserForm;
             $article = $this->loadModel($id);  

             if (isset($_POST['ArticleUserForm'])){
                 $form->attributes = $_POST['ArticleUserForm'];
                 $form->article = $article;

                 //validate user input and set a sucessful flash mesage
                 if ($form->validate()){
                     Yii::app()->user->setFlash('success', $form->username . " has
                          been added to the topic.");
                      
                     //update editor_id or approver_id in tbl_article
                     $user_id = User::model()->findByAttributes(array('username'=>$form->username))->id;
                     if ($form->role == 'editor'){
                         $article->editor_id = $user_id;
                     }
                     else if ($form->role == 'approver'){
                         $article->approver_id = $user_id;
                     }
                     $article->save(false);

                     $form = new ArticleUserForm;
                 }
             }
             //display the add user form
             $users = User::model()->findAll();
             $usernames = array();
             foreach ($users as $user){
//                 uncomment this to allow searching for 'admin' username
//                 if ($user->username != 'admin')
                    $usernames[] = $user->username;
             }

             $form->article = $article;
             $this->render('adduser', array(
                 'model'=>$form,
                 'usernames'=>$usernames,
             ));
        }

        private function updateTbl($article, $role, $username){
            $sql = 'UPDATE tbl_article_user_assignment
                SET create_time=:createTime, update_time=:updateTime,
                create_user_id=:createUserId, update_user_id=:updateUserId
                WHERE user_id=:userId AND article_id=:articleId';
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":createTime", new CDbExpression("NOW()"));
            $command->bindValue(":updateTime", new CDbExpression("NOW()"));
            $command->bindValue(":createUserId", Yii::app()->user->id, PDO::PARAM_INT);
            $command->bindValue(":updateUserId", Yii::app()->user->id, PDO::PARAM_INT);
            $command->bindValue("userId", User::model()->findByAttributes(array("username"=> $this->username)), PDO::PARAM_INT);
            $command->bindValue("articleId", $this->article->id, PDO::PARAM_INT );
            return $command->execute();
        }




	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Article');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article']))
			$model->attributes=$_GET['Article'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
